<template>
  <div class="page">
    <el-button @click='fetchTest'>baidu</el-button>
    <el-link href='https://wwww.baidu.com'>百度</el-link>
    <QueryForm
      @getData="getData"
      v-model:queryData="queryData"
      :fields="fields"
    >
      <template v-slot:name="{ item }">
        <el-input v-model="item.name" />
      </template>

        <template v-slot:classesId="{ item }">
          <el-select v-model='item.classesId'>
            <el-option
                v-for="classes in classesList"
                :key="classes.id"
                :label="classes.name"
                :value="classes.id"
              />
          </el-select>
      </template>
    </QueryForm>
    <div class="container">
      <div class='mb-8'>
        <el-button @click="copyToRedis">同步数据到redis</el-button>
        <el-button class=' mr-8' type='primary' @click="showForm('add')">新增</el-button>
        <Upload />
      </div>
      <BaseTable
        border
        :columns="columns"
        :source="table.list"
        :isMutiple="false"
        :total="table.total"
        @paginationChange="handlePaginationChange"
        :pageNum="table.pageNum"
        :pageSize="table.pageSize"
        v-model:multipleSelection='table.multipleSelection'
      >
      <template v-slot:createdAt='scope'>
        <div>{{ parseTime(scope.row.createdAt)  }}</div>
      </template>

      <template v-slot:classesId='scope'>
        <div>{{ idsTolabel(scope.row.classesId)  }}</div>
      </template>

      <template v-slot:price='scope'>
        <div>{{ scope.row.price.toFixed(2 )  }} 元</div>
      </template>

        <template v-slot:action="scope">
          <el-button size="mini"  @click="showForm('edit',scope.row)" type="primary">编辑</el-button>
          <el-button size="mini" type="danger"  @click='deleteItems(scope.row)'>删除</el-button>
        </template>
      </BaseTable>
    </div>

    <UserForm @refresh="getData" v-model:visible='visible' :title='formTitle' :data='formData' />
  </div>
</template>

<script lang="ts">
import { computed, defineComponent, onMounted, readonly, ref } from 'vue'
import QueryForm from '@/components/form/query/index.vue'
import BaseTable from '@/components/table/index.vue'
import UserForm from './from.vue'
import useTable from '@/use/useTable'
import { parseTime } from '@/utils'
import { getGoodsList, goodsDelete } from '@/api/goods'
import { getClassesList } from '@/api/classes'
import Upload from '@/components/upload/index.vue'
export default defineComponent({
  name: 'User',
  components: {
    QueryForm,
    BaseTable,
    UserForm,
    Upload,
  },
  setup () {
    const visible = ref(false) // 编辑表单显示
    const formData = ref({}) // 表单数据
    const formType = ref('')
    const classesList = ref([])

    const fields = readonly([
      {
        label: '商品名称',
        value: 'name',
        slot: true,
      },
      {
        label: '所属分类',
        value: 'classesId',
        slot: true,
      },
    ])
    const queryData = ref({
      name: '',
      classesId: null,
    })
    const columns = readonly([
      {
        value: 'id',
        label: '编号',
      },
      {
        value: 'brand',
        label: '商品品牌',
      },
      {
        value: 'name',
        label: '商品名称',
      },
      {
        value: 'price',
        label: '商品价格',
        slot: true,
      },
      {
        value: 'unit',
        label: '商品单位',
      },
      {
        value: 'weight',
        label: '商品规格',
      },
      {
        value: 'stock',
        label: '商品库存',
      },
      {
        value: 'classesId',
        label: '所属分类',
        slot: true,
      },
      {
        value: 'desc',
        label: '商品描述',
      },
      {
        value: 'createdAt',
        label: '创建时间',
        slot: 'createdAt',
      },
      {
        value: 'action',
        label: '操作',
        slot: true,
      },
    ])

    const formTitle = computed(() => {
      return formType.value === 'add' ? '新增商品' : '编辑商品'
    })

    function handlePaginationChange (data) {
      table.value.params = { ...table.value.params, ...data }
      getData()
    }
    function getData () {
      getList(getGoodsList, { ...queryData.value, ...table.value.params })
    }

    async function getClasses () {
      const data = await getClassesList() as any
      console.log('getClasses', data)
      classesList.value = data.rows || []
    }

    function idsTolabel (ids) {
      const list = [...ids].sort((a, b) => a - b)
      let index = 0
      const result = []

      for (const item of classesList.value) {
        const { id, name } = item
        if (list[index] === id) {
          result.push(name)
          index++
        }
      }
      return result.join(',')
    }

    function showForm (type:string, data) {
      console.log('table', type, data)
      formType.value = type
      if (type === 'add') {
        formData.value = {}
      } else {
        formData.value = { ...data }
      }
      visible.value = true
    }

    const { table, getList, handleDelete } = useTable()

    async function deleteItems (row) {
      await handleDelete(goodsDelete, [row.id])
      getData()
    }

    async function copyToRedis () {
      console.log('copyToRedis')
    }

    function fetchTest () {
      fetch('https://www.baidu.com/').then(res => {
        console.log('res', res)
      })
    }
    onMounted(async () => {
      await getClasses()
      getData()
    })

    return {
      fields,
      queryData,
      columns,
      table,
      visible,
      formData,
      formTitle,
      classesList,
      deleteItems,
      getData,
      handlePaginationChange,
      showForm,
      parseTime,
      idsTolabel,
      copyToRedis,
      fetchTest,
    }
  },
})
</script>

  <style lang='less' scoped>

</style>
